package zhihui.mobile.task;

import android.content.Context;
import android.os.AsyncTask;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.log4j.Logger;

import java.io.InputStream;
import java.util.List;

import zhihui.mobile.bean.address.Province;
import zhihui.mobile.manager.address.AddressManager;

/**
 * Created by 张公铭 on 2017/8/28 0028.
 */

public class AreaLoadTask extends AsyncTask<Void, Void, Boolean>
{
    private Logger logger = Logger.getLogger(AreaLoadTask.class);
    private Context mContext;
    private ICallBackListener mListener;

    public interface ICallBackListener
    {
        void finish(boolean result);
    }

    public AreaLoadTask(Context context, ICallBackListener listener)
    {
        mContext = context;
        mListener = listener;
    }

    @Override
    protected void onPreExecute()
    {

    }

    @Override
    protected Boolean doInBackground(Void... params)
    {
        try
        {
            InputStream is = mContext.getAssets().open("area.json");
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            is.close();
            String json = new String(bytes);
            Gson gson = new Gson();
            List<Province> list = gson.fromJson(json, new TypeToken<List<Province>>()
            {
            }.getType());
            AddressManager.getInstance().setmAddressList(list);
            return true;
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("解析地区文件错误：" + e.getMessage());
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean bool)
    {
        mListener.finish(bool);
    }
}
